//
//  LocationService.m
//  MexicoLoan
//
//  Created by WXP on 2025/2/27.
//
//

#import "LocationService.h"

@interface LocationService ()

@property (nonatomic, assign) bool need;
@property (nonatomic, copy) dispatch_block_t doup;

@end

@implementation LocationService
{
    CLLocationManager *_locationManager;
}

+ (instancetype)sharedInstance {
    static LocationService *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 10;
        // 检查授权状态
        [self checkAuthorizationStatus];
    }
    return self;
}

- (void)checkAuthorizationStatus {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined) {
        [_locationManager requestWhenInUseAuthorization];
    } else if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if ([GlobalMethod readBoolLocal:LOCAL_AGREE_GPSLOCATION_AUTH] == false){
                [GlobalMethod writeBool:true local:LOCAL_AGREE_GPSLOCATION_AUTH];
                [GlobalMethod hitPointWithPageName:KEY_GpsLocation action:KEY_agreeGpsLocationAuth extInfo:nil];
            }
        });
        [self startUpdatingLocation];
    } else if (status == kCLAuthorizationStatusDenied) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if ([GlobalMethod readBoolLocal:LOCAL_REFUSE_GPSLOCATION_AUTH] == false){
                [GlobalMethod writeBool:true local:LOCAL_REFUSE_GPSLOCATION_AUTH];
                [GlobalMethod hitPointWithPageName:KEY_GpsLocation action:KEY_refuseGpsLocationAuth extInfo:nil];
            }
        });
    }
}

- (void)startUpdatingLocation {
    [_locationManager startUpdatingLocation];
}

- (void)startUploca:(dispatch_block_t)doup {
    [_locationManager startUpdatingLocation];
    self.need = true;
    self.doup = doup;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.need = false;
        doup();
    });
}

- (CLLocationCoordinate2D)getCurrentLocation {
    return _currentLocation;
}

// CLLocationManagerDelegate 方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = [locations lastObject];
    _currentLocation = newLocation.coordinate;
    if(self.doup){
        self.need = false;
        self.doup();
    }
    // NSLog(@" --- 经纬度获取成功 --- : %f, %f", _currentLocation.latitude, _currentLocation.longitude);
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    // NSLog(@" --- 经纬度获取失败 --- : %@", error.localizedDescription);
}

// 处理授权状态变化
- (void)locationManagerDidChangeAuthorization:(CLLocationManager *)manager {
    [self checkAuthorizationStatus];
}


@end
